<template>
    <div>
        <el-form
            ref="form1"
            :model="form"
            label-width="120px"
            label-position="right"
        >
            <el-row :gutter="30">
                <el-col :span="24">
                    <el-form-item
                        label="租赁合同模板"
                        prop="newTemplateObj.contractTemplateId"
                        :rules="
                            _from == 'apply'
                                ? [
                                      {
                                          required: true,
                                          message: '请选择租赁合同模板',
                                          trigger: 'change',
                                      },
                                  ]
                                : []
                        "
                    >
                        <div>
                            <el-select
                                v-model="form.newTemplateObj.contractTemplateId"
                                value-key="value"
                                placeholder="请选择租赁合同模板"
                                clearable
                                @change="selectTemplate"
                                @visible-change="focusTemplate"
                                :loading="loading"
                                :disabled="state == 'readonly'"
                            >
                                <el-option-group
                                    v-for="group in list"
                                    :key="group.label"
                                    :label="group.label"
                                    v-if="
                                        group.options &&
                                        group.options.length > 0
                                    "
                                >
                                    <el-option
                                        v-for="item in group.options"
                                        :key="item.value"
                                        :label="item.label"
                                        :value="item.value"
                                    >
                                    </el-option>
                                </el-option-group>
                            </el-select>
                            <el-button
                                v-if="
                                    form.newTemplateObj &&
                                    form.newTemplateObj.contractTemplateId
                                "
                                style="margin-left: 15px"
                                type="text"
                                @click="goTemplateDetail"
                                >查看</el-button
                            >
                            <el-button
                                v-if="
                                    form.newTemplateObj &&
                                    form.newTemplateObj.contractTemplateId &&
                                    type == 'preview'
                                "
                                style="margin-left: 15px"
                                type="text"
                                @click="downloadTemplate"
                                >下载</el-button
                            >
                        </div>
                    </el-form-item>
                </el-col>
                <!-- <el-col :span="24"> -->
                <!-- <el-form-item label="说明" prop="remark"> -->
                <!-- <el-input type="textarea" placeholder="请输入说明" v-model="form.remark" maxlength="500" :rows="5" show-word-limit></el-input> -->
                <!-- </el-form-item> -->
                <!-- </el-col> -->
                <!-- <el-col :span="24"> -->
                <!-- <el-form-item label="附件" prop="annex"> -->
                <!-- <image-common :up-type="2" v-model="form.annex" info="上传附件"></image-common> -->
                <!-- </el-form-item> -->
                <!-- </el-col> -->
            </el-row>
        </el-form>
    </div>
</template>

<script>
import { otherOptionalTemplates } from "@/api/contractTemplate/templateUpdate";
export default {
    components: {},
    props: {
        currTemplate: {
            type: [String, Number],
            default: "",
        },
        customerId: {
            type: [String, Number],
            default: "",
        },
        planID: {
            required: false,
        },
        newOrOldCars: {
            required: false,
        },
        customerTypeCode: {
            required: false,
        },
        state: {
            required: false,
        },
        type: {
            required: false,
        },
    },
    data() {
        return {
            form: {
                newTemplateObj: {
                    contractTemplateId: "",
                    contractTemplateCode: "",
                    contractTemplateName: "",
                    raw: {},
                },
                remark: null,
                annex: null,
            },
            rules: {
                newTemplateObj: [
                    {
                        required: true,
                        message: "请选择合同模版方案",
                        trigger: "blur",
                    },
                ],
                remark: [
                    { required: true, message: "请输入说明", trigger: "blur" },
                ],
            },
            list: [],
            loading: false,
        };
    },
    inject: ["details_forecast", "_from"],
    watch: {
        customerId: {
            handler(val) {
                if (this.notEmpty(val)) {
                    this.getTemplateList();
                } else {
                    this.list = [];
                }
            },
            immediate: true,
        },
        planID: {
            handler(val) {
                if (this.notEmpty(this.customerId)) {
                    this.getTemplateList();
                }
            },
        },
        newOrOldCars: {
            handler(val) {
                if (this.notEmpty(this.customerId)) {
                    this.getTemplateList();
                }
            },
        },
        customerTypeCode: {
            handler(val) {
                if (this.notEmpty(this.customerId)) {
                    this.getTemplateList();
                }
            },
        },
    },
    computed: {
        details() {
            return this.details_forecast();
        },
    },
    methods: {
        downloadTemplate() {
            this.$emit(
                "downTemplate",
                this.form?.newTemplateObj?.contractTemplateId
            );
        },
        focusTemplate(state) {
            if (state && !this.details?.leaseeId) {
                this.$message({
                    message: "请先选择承租方",
                    type: "warning",
                });
            }
        },
        initForm() {
            console.log("initForm");
            this.form = {
                newTemplateObj: {
                    contractTemplateId: "",
                    contractTemplateCode: "",
                    contractTemplateName: "",
                    raw: {},
                },
                remark: null,
                annex: null,
            };
        },
        selectTemplate(val) {
            let arr = [];
            this.list.map((item) => {
                item?.options?.map((e) => {
                    arr.push(e);
                });
            });
            let item = arr.find((e) => {
                return e.value?.toString() == val?.toString();
            });
            if (item) {
                this.form.newTemplateObj.contractTemplateCode =
                    item.templateCode;
                this.form.newTemplateObj.contractTemplateName = item.label;
                this.form.newTemplateObj.raw = item;
            }
        },
        //获取其他生效合同模版
        getTemplateList() {
            if (this.loading) {
                return;
            }
            this.form.newTemplateObj = {
                contractTemplateId: "",
                contractTemplateCode: "",
                contractTemplateName: "",
                raw: {},
            };

            this.loading = true;
            otherOptionalTemplates({
                currTemplate: this.currTemplate,
                customerId: this.customerId,
                planId: this.planID,
                newOrOldCars: this.newOrOldCars,
                customerType: this.customerTypeCode,
            })
                .then((res) => {
                    this.list = res.data;
                })
                .finally(() => {
                    this.loading = false;
                });
        },
        // 查看合同模版详情
        goTemplateDetail() {
            this.$emit(
                "getContractContent",
                this.form.newTemplateObj.contractTemplateId
            );
        },
        saveForm(type) {
            let flag = false;
            if (type == "save") {
                flag = true;
            } else {
                this.$refs["form1"].validate((valid) => {
                    if (valid) {
                        flag = true;
                    }
                });
            }
            if (flag) {
                return this.form;
            }
        },
        valid() {
            return new Promise(async (resolve) => {
                let result = true;
                let refs = Object.values(this.$refs);
                for (let index = 0; index < refs?.length; index++) {
                    const ref = refs[index];
                    if (
                        Object.prototype.toString.call(ref) == "[object Array]"
                    ) {
                        for (let i = 0; i < ref.length; i++) {
                            const element = ref[i];
                            if (element?.valid) {
                                let rc = await element?.valid?.();
                                result = result && rc;
                            }
                            if (element?.validate) {
                                let rf = await this._valid(ref);
                                result = result && rf;
                            }
                            if (element?.form_validate) {
                                let rf = await this._valid(
                                    ref,
                                    "form_validate"
                                );
                                result = result && rf;
                            }
                        }
                    } else {
                        if (ref?.valid) {
                            let rc = await ref?.valid?.();
                            result = result && rc;
                        }
                        if (ref?.validate) {
                            let rf = await this._valid(ref);
                            result = result && rf;
                        }
                        if (ref?.form_validate) {
                            let rf = await this._valid(ref, "form_validate");
                            result = result && rf;
                        }
                    }
                }

                resolve(result);
            });
        },
    },
    mounted() {
        this.refRedirect.call(this, "form1");
        // this.getTemplateList();
    },
};
</script>

<style lang="scss" scoped></style>
